<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 搜索添加 -->
      <div style="margin-top: 15px">
        <el-input
          v-model="searchInput"
          placeholder="请输入用户名搜索内容"
          label-width="120px"
          class="input-with-select search_input"
          :clearable="true"
          @clear="getUserList"
        >
        </el-input>
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="search"
        ></el-button>
        <el-button @click="addUser" type="primary">添加用户</el-button>
      </div>

      <!-- 用户列表 -->
      <!-- <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="date" label="日期" width="180">
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="address" label="地址"> </el-table-column>
      </el-table> -->
      <el-table
        id="EditSelect"
        v-loading="tableLoading"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        :data="tableData"
        :header-cell-style="{
          color: '#606266',
          textAlign: 'center',
        }"
        :cell-style="{ textAlign: 'center', padding: '5px 0', height: '30px' }"
        :row-style="{ height: '48px' }"
        empty-text="Current page has no data"
      >
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          min-width="100"
        ></el-table-column>

        <el-table-column
          prop="email"
          label="邮箱"
          min-width="120"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          min-width="100"
        ></el-table-column>
        <el-table-column
          prop="role_name"
          label="用户角色"
          min-width="100"
        ></el-table-column>
        <el-table-column prop="mg_state" label="状态" min-width="60">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#5a9cf8"
              inactive-color="#ff4949"
              @change="changeUserStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column class="btn" min-width="100">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="" label="Operation" min-width="130">
          <template slot-scope="scope">
            <el-link
              type="primary"
              :underline="false"
              style="text-decoration: underline"
              @click="raNoClick(scope.row.id)"
              >Edit</el-link
            >
            <span style="color: #409eff"> | </span>
            <el-link
              type="primary"
              :underline="false"
              style="text-decoration: underline"
              @click="deleteTableRow(scope.row.id)"
              >Delete</el-link
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :total="pageInfo.total"
        :page-sizes="[3, 5, 10]"
        :page-size="pageInfo.pageSize"
        style="float: right"
        @current-change="changeCurrentPage"
        @size-change="changeSizePage"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button class="cancelButton" @click="closeForm('ruleForm')"
          >cancel</el-button
        >
        <el-button type="primary" @click="submitForm('ruleForm')"
          >confirm</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改用户 -->
    <el-dialog
      title="修改用户"
      :visible.sync="dialogVisibleEdit"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeForm('ruleForm')">cancel</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >confirm</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：<el-select v-model="value" placeholder="请选择角色">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeRoleForm()">cancel</el-button>
        <el-button type="primary" @click="submitRoleForm()">confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //验证邮箱
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    var checkModeile = (rule, value, cb) => {
      const regMobile = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的电话'))
    }
    return {
      pageInfo: {
        total: 0,
        pageSize: 3,
        currentPage: 1,
      },
      tableData: [], //用户数据
      tableLoading: false,
      searchInput: '',
      dialogVisible: false,
      dialogVisibleEdit: false,
      setRoleDialogVisible: false,
      uId: '',
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkModeile, trigger: 'blur' },
        ],
      },
      //分配权限userInfo
      userInfo: {},
      //分配权限下拉框
      value: '',
      options: [],
    }
  },
  created() {
    this.getUserList()
    this.getRole()
  },
  methods: {
    async getRole() {
      const { data: res } = await this.$http.get('roles')
      this.options = res.data
      console.log(this.options)
    },
    async getUserList() {
      let _self = this
      let query = {
        query: _self.searchInput,
        pagenum: _self.pageInfo.currentPage,
        pagesize: _self.pageInfo.pageSize,
      }
      const { data: res } = await this.$http.get('users', { params: query })
      console.log(res)
      _self.pageInfo.total = res.data.total
      _self.tableData = res.data.users
    },
    //编辑用户
    async raNoClick(a) {
      this.uId = a
      const { data: res } = await this.$http.get(`users/${a}`)
      this.ruleForm = res.data
      console.log(this.ruleForm)
      this.dialogVisibleEdit = true
    },
    //添加用户
    addUser() {
      this.dialogVisible = true
    },
    //删除用户
    deleteTableRow(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await this.$http.delete('users/' + id)
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //翻页
    changeCurrentPage(val) {
      console.log(val)
      this.pageInfo.currentPage = val
      this.getUserList()
    },
    changeSizePage(val) {
      this.pageInfo.pageSize = val
      this.getUserList()
    },
    //用户状态的修改
    async changeUserStatus(row) {
      console.log(row)
      var query = {
        uId: row.id,
        type: row.mg_state,
      }
      const { data: res } = await this.$http.put(
        `users/${query.uId}/state/${query.type}`
      )
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    //搜索
    async search() {
      this.pageInfo = {
        total: 0,
        pageSize: 3,
        currentPage: 1,
      }
      this.getUserList()
    },
    handleClose(done) {
      this.setRoleDialogVisible = false
      this.dialogVisible = false
      this.dialogVisibleEdit = false
      this.ruleForm = {
        username: '',
        password: '',
        email: '',
        mobile: '',
      }
    },

    submitForm(ruleForm) {
      console.log(this.dialogVisible)
      console.log(this.dialogVisibleEdit)
      console.log(this.ruleForm)
      console.log(this.uId)
      if (this.dialogVisible) {
        this.$refs[ruleForm].validate(async (valid) => {
          if (valid) {
            const { data: res } = await this.$http.post('users', this.ruleForm)
            console.log(res)
            this.dialogVisible = false
            this.ruleForm = {
              username: '',
              password: '',
              email: '',
              mobile: '',
            }
            this.getUserList()
            this.$message.success('添加用户成功!')
          }
        })
      }

      if (this.dialogVisibleEdit) {
        this.$refs[ruleForm].validate(async (valid) => {
          if (valid) {
            console.log(this.ruleForm)
            const { data: res } = await this.$http.put(
              'users/' + this.ruleForm.id,
              { email: this.ruleForm.email, mobile: this.ruleForm.mobile }
            )
            console.log(res)
            this.dialogVisibleEdit = false
            this.getUserList()
            this.$message.success('修改用户成功!')
          }
        })
      }
    },
    closeForm(ruleForm) {
      // this.$refs[ruleForm].resetFields()
      this.ruleForm = {
        username: '',
        password: '',
        email: '',
        mobile: '',
      }
      this.dialogVisible = false
      this.dialogVisibleEdit = false
    },
    //分配权限按钮
    setRole(userInfo) {
      this.userInfo = userInfo
      this.setRoleDialogVisible = true
    },
    //关闭分配权限
    async submitRoleForm() {
      console.log(this.value)
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        { id: this.userInfo.id, rid: this.value }
      )
      console.log(res)
      this.setRoleDialogVisible = false
      this.getUserList();
    },
    closeRoleForm() {
      this.setRoleDialogVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.input-with-select {
  width: 300px;
  margin-right: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 20px;
}
.search_input {
  width: 400px;
}
</style>
